package com.niiwoo.civet.trade.service.local.mail;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;

import javax.mail.internet.MimeMessage;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.niiwoo.civet.trade.enums.TradeEmailEnum;
import com.niiwoo.tripod.provider.exception.BizException;

/**
 * 邮件发送服务 
 *
 * @author: kevin.jia
 * @version 1.0.0
 */
@Service
public class MailSendService {

	@Value("${spring.mail.username}")
	private String fromEmail;
	
	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	private TemplateEngine templateEngine;
	
	/**
	 * 发送简单邮件
	 * 
	 * @param sendTo
	 * @param title
	 * @param content
	 */
	public void sendSimpleMail(String sendTo, String title, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(fromEmail);
		
		message.setTo(bulidSendToList(sendTo));
		message.setTo(sendTo);
		message.setSubject(title);
		message.setText(content);
		mailSender.send(message);
	}
	
	/**
	 * 发送模板邮件
	 * 
	 * @param tradeEmailEnum
	 * 				交易中心邮件枚举
	 * @param paramMap
	 * 				请求参数
	 */
	public void sendTemplateMail(TradeEmailEnum tradeEmailEnum, Map<String, Object> paramMap) {
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(fromEmail);
			helper.setTo(bulidSendToList(tradeEmailEnum.getSendTo()));
			helper.setSubject(tradeEmailEnum.getSubject());
			helper.setText(generateEmailForHtml(tradeEmailEnum.getTemplateName(), paramMap), true);
		} catch (Exception e) {
		}
		mailSender.send(mimeMessage);
	}
	
	/**
	 * 根据模板生成邮件内容
	 * 
	 * @param templateName
	 *            模板名称，默认路径：src/main/resource/templates
	 * @param comtent
	 *            业务参数
	 * @return
	 */
	private String generateEmailForHtml(String templateName, Map<String, Object> paramMap) {
		Context context = new Context();
		
		// 根据请求MAP参数构建Context对象		
		if (MapUtils.isNotEmpty(paramMap)) {
			for (Entry<String, Object> entry : paramMap.entrySet()) {
				context.setVariable(entry.getKey(), entry.getValue());
			}			
		}

		// 生成邮件内容
		return templateEngine.process(templateName, context);
	}
	
	/**
	 * 构建收件人列表
	 * 
	 * @param sendTo
	 * @return
	 */
	private String[] bulidSendToList(String sendTo) {
		Optional.ofNullable(sendTo).orElseThrow(() -> new BizException(""));
		return sendTo.split(";");
	}
}